import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { ROLES_KEY } from "src/decorators/check-roles.decorator";

@Injectable()
export class RolesGuard implements CanActivate {
    constructor(private readonly reflector: Reflector) { }
    canActivate(context: ExecutionContext): boolean {
        // get marked roles from controller or methods
        const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
            context.getHandler(),
            context.getClass(),
        ]);
        console.log("🚀 ~ RolesGuard ~ canActivate ~ requiredRoles:", requiredRoles) // [ 'admin' ]


        // 1. if no roles marked, then allow access
        if (!requiredRoles) {
            return true;
        }
        // 2. get user from request
        const { user } = context.switchToHttp().getRequest();
        console.log("🚀 ~ RolesGuard ~ canActivate ~ user:", user)

        // 3. validate if role in allowed role list
        if (!user?.roles) {
            return false;
        }
        return requiredRoles.some((role) => user?.roles.includes(role));
    }
}